package com.qys.livesMall.anchor.task;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.qys.livesMall.anchor.business.AnchorLivesBusiness;
import com.qys.livesMall.anchor.controller.LiveStreamUtils;
import com.qys.livesMall.anchor.model.entity.AnchorLivesSession;
import com.qys.livesMall.anchor.service.AnchorLivesSessionService;
import com.qys.livesMall.cache.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


/**
 * 直播状态监测任务（断流大于30分钟，终止本场直播）
 * @author yxh
 */
@Slf4j
@Component
public class LiveTaskSettlement {

    private final static String REDIS_LOCK_KEY = "liveStatusMonitor_lock";

    @Autowired
    private AnchorLivesSessionService livesSessionService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private AnchorLivesBusiness anchorLivesBusiness;
    /**
     * 当前环境
     */
    @Value("${spring.profiles.active}")
    private String profile;

    @Scheduled(cron = "0 0/1 * * * ? ") // 每分钟执行
    public void monitor() {

        if("dev".equalsIgnoreCase(profile)){
            return;
        }

        try {
            //获取锁
            boolean lock = redisCache.lock(REDIS_LOCK_KEY, 1, 50);
            if(!lock){
                return;
            }
            //获取所有直播中的场次
            List<AnchorLivesSession> livingRoom = livesSessionService.list(Wrappers.<AnchorLivesSession>lambdaQuery().eq(AnchorLivesSession::getLivesStatus, (byte) 2).isNotNull(AnchorLivesSession::getDepartureTime));
            if(CollectionUtils.isEmpty(livingRoom)){
                return;
            }

            //30分钟前断流的直播场次id
            List<Long> todoList = livingRoom.stream().filter(e ->e.getDepartureTime().isBefore(LocalDateTime.now().minusMinutes(30))).map(AnchorLivesSession::getId).toList();
            List<Long> logList = Lists.newArrayList();
            if(CollectionUtils.isEmpty(todoList)){
                return;
            }
            log.info("start liveStatusMonitor");
            //断流超时30分钟，关闭直播间
            for (Long sessionId : todoList) {
                String id = anchorLivesBusiness.getUserIdByLivesSessionId(sessionId);
                if(StringUtils.isEmpty(id)){
                    continue;
                }
                boolean living = LiveStreamUtils.checkIfItSLive(id);
                if(!living){
                    AnchorLivesSession session = livesSessionService.getById(sessionId);
                    anchorLivesBusiness.closeLive(Long.valueOf(id), true, session.getDepartureTime());
                    logList.add(sessionId);
                }
            }
            log.info("end liveStatusMonitor, task:{}", logList);
            //释放锁
            redisCache.deleteLock(REDIS_LOCK_KEY);
        } catch (Exception e) {
            log.error("error liveStatusMonitor:{}", e.getMessage());
        }
    }
}

